package io.xccit.securityauthctrl.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.xccit.securityauthctrl.entity.User;
import io.xccit.securityauthctrl.mapper.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author CH_ywx
 * @date 2023-06-04
 * @description
 */
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",s);
        User user = userMapper.selectOne(queryWrapper);
        if(null == user){
            throw new UsernameNotFoundException("用户名不存在!");
        }
//        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");//给用户设置的权限(此时权限为admin,没有admins)
//        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins"); //此时权限为admins
        //注意:配置角色时前面需要添加前缀ROLE_   参考过滤器中的源码
        List<GrantedAuthority> authRoles = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");//此时权限为admins,角色为sale
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                new BCryptPasswordEncoder().encode(user.getPassword()),
                authRoles
        );
    }
}
